package org.springframework.android.showcase.rest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.android.showcase.AbstractAsyncListActivity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import org.springframework.android.showcase.R;
//import org.springframework.android.showcase.rest.HttpGetJsonActivity.DownloadStatesTask;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;


public class Subir_Utpl extends AbstractAsyncListActivity{//AbstractAsyncActivity
	
	
	/*protected static final String TAG = EnviarDatos.class.getSimpleName();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.subirbus_utpl);
		new PostMessageTask().execute();
	}

	// ***************************************
	// Private methods
	// ***************************************
	private void showResult(String result) {
		// display a notification to the user with the response message
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	// ***************************************
	// Private classes
	// ***************************************
	private class PostMessageTask extends AsyncTask<Void, Void, String> {

		private String text;

		@Override
		protected void onPreExecute() {
			showLoadingProgressDialog();

			// retrieve the message text from the EditText field
			EditText editText = (EditText) findViewById(R.id.edit_text_message);

			//text = editText.getText().toString();
			text="Sube utpl";
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				// The URL for making the POST request
				final String url = getString(R.string.base_uri) + "/sendmessage";

				// Create a new RestTemplate instance
				RestTemplate restTemplate = new RestTemplate();
				restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

				// Make the network request, posting the message, expecting a String in response from the server
				String response = restTemplate.postForObject(url, text, String.class);

				// Return the response body to display to the user
				return response;
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			showResult(result);
		}

	}*/
	
	protected static final String TAG = GoogleSearchGsonActivity.class.getSimpleName();

	private List<GoogleSearchResult> results;

	// ***************************************
	// Activity methods
	// ***************************************
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onStart() {
		super.onStart();
		// when this activity starts, initiate an asynchronous HTTP GET request
		new GoogleSearchTask().execute();
		new DownloadStatesTask().execute();
	}

	
	
	// ***************************************
	// Private methods
	// ***************************************
	private void refreshStates(List<State> states) {
		if (states == null) {
			return;
		}

		StatesListAdapter adapter = new StatesListAdapter(this, states);
		setListAdapter(adapter);
	}

	// ***************************************
	// Private classes
	// ***************************************
	private class DownloadStatesTask extends AsyncTask<Void, Void, List<State>> {

		@Override
		protected void onPreExecute() {
			showLoadingProgressDialog();
		}

		@Override
		protected List<State> doInBackground(Void... params) {
			try {
				// The URL for making the GET request
				final String url = getString(R.string.base_uri) + "/recorridos";

				// Set the Accept header for "application/json"
				HttpHeaders requestHeaders = new HttpHeaders();
				List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
				acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
				requestHeaders.setAccept(acceptableMediaTypes);

				// Populate the headers in an HttpEntity object to use for the request
				HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

				// Create a new RestTemplate instance
				RestTemplate restTemplate = new RestTemplate();
				restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

				// Perform the HTTP GET request
				ResponseEntity<State[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
						State[].class);

				// convert the array to a list and return it
				
				return Arrays.asList(responseEntity.getBody());
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}

			return null;
		}

		@Override
		protected void onPostExecute(List<State> result) {
			dismissProgressDialog();
			refreshStates(result);
		}

									
	}
	
	
	
	
	
	// ***************************************
	// ListActivity methods
	// ***************************************
	@Override
	protected void onListItemClick(android.widget.ListView l, android.view.View v, int position, long id) {
		if (this.results == null) {
			return;
		}
		AdapterView<?> parentView = null;
		switch(position){
		case 0:
			startActivity(new Intent(parentView.getContext(), JsonXmlActivity.class));
			break;
			
		default:
			break;
		}

		GoogleSearchResult result = this.results.get(position);
		//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(result.getUrl())));
		startActivity(new Intent(parentView.getContext(), JsonXmlActivity.class));
	}
	
	
	

	// ***************************************
	// Private methods
	// ***************************************
	private void refreshResults(GoogleSearchResponse response) {
		if (response == null) {
			return;
		}

		this.results = response.getResponseData().getResults();
		setListAdapter(new GoogleSearchResultListAdapter(this, this.results));
	}

	
	
	// ***************************************
	// Private classes
	// ***************************************
	private class GoogleSearchTask extends AsyncTask<Void, Void, GoogleSearchResponse> {

		@Override
		protected void onPreExecute() {
			showLoadingProgressDialog();
		}

		@Override
		protected GoogleSearchResponse doInBackground(Void... params) {
			try {
				// The URL for making the GET request
				//http://localhost:8080/server/resources/org.springframework.entidades.recorridos/
				final String url = getString(R.string.base_uri)+"/resources/org.springframework.entidades.recorridos/";

				// Create a new RestTemplate instance
				RestTemplate restTemplate = new RestTemplate();

				// Set a custom GsonHttpMessageConverter that supports the text/javascript media type
				GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
				messageConverter.setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "javascript")));
				restTemplate.getMessageConverters().add(messageConverter);

				// Perform the HTTP GET request to the Google search API
				GoogleSearchResponse response = restTemplate.getForObject(url, GoogleSearchResponse.class,
						"Google Android");

				return response;
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}

			return null;
		}

		@Override
		protected void onPostExecute(GoogleSearchResponse response) {
			dismissProgressDialog();
			refreshResults(response);
		}

	}
	

}
